package pers.dawnyang.config.security;

import java.util.Comparator;
import java.util.List;
import cn.dev33.satoken.stp.StpUtil;
import pers.dawnyang.common.core.enums.ResultEnum;
import pers.dawnyang.config.SpringUtil;
import pers.dawnyang.config.exception.BusinessException;
import pers.dawnyang.modular.system.domain.common.RoleInfo;
import pers.dawnyang.modular.system.domain.common.UserInfo;
import pers.dawnyang.modular.system.service.SystemService;

/**
 * @author dawn yang
 * @date 2022/05/31
 */
public class SecurityUtil {

  private static SystemService systemService = SpringUtil.getBean(SystemService.class);

  // 获得当前用户最大的角色等级
  public static Long getUserMinRoleLevel() {
    String userCode = (String) StpUtil.getLoginId();
    UserInfo user = systemService.getUserInfo(userCode);
    if (null == user) {
      throw new BusinessException(ResultEnum.ERROR_SESSION_EXPIRES);
    }
    List<RoleInfo> roleList = user.getRoleList();
    // 数值越小，等级越高
    Long minRoleSort =
        roleList.stream().min(Comparator.comparing(RoleInfo::getRoleSort)).get().getRoleSort();
    return minRoleSort;
  }


  public static Long getUserId() {
    String userCode = (String) StpUtil.getLoginId();
    UserInfo user = systemService.getUserInfo(userCode);
    return user.getUserId();
  }

}
